#include "LayerFeatureParser.h"

#include "SetParser.h"
#include "QStringParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

LayerFeatureParser::LayerFeatureParser(
    QStringParser *&_layerRefParser
    , SetParser *&_setParser
):    m_layerRefParser(_layerRefParser)
    , m_setParser(_setParser)
{

}

bool LayerFeatureParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new LayerFeature());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("layerRef")))
    {
        data = reader->attributes().value(QStringLiteral("layerRef"));
        if (!m_layerRefParser->parse(reader, data))
            return false;
        m_result->layerRef = m_layerRefParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("layerRef: Attribute is required"));
        return false;
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
        if (name == QStringLiteral("Set"))
        {
            if (!m_setParser->parse(reader))
                return false;
            auto result = m_setParser->result();
            m_result->setList.append(result);
        }
        else
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

LayerFeature *LayerFeatureParser::result()
{
    return m_result.take();
}

}